package cn.edu.whu.forecast.controller;

import cn.edu.whu.forecast.common.PageBean;
import cn.edu.whu.forecast.common.ResultBean;
import cn.edu.whu.forecast.entity.mysql.SectionFlowWaterLevel;
import cn.edu.whu.forecast.entity.mysql.WarningRecord;
import cn.edu.whu.forecast.service.impl.LogMessageServiceImpl;
import cn.edu.whu.forecast.service.impl.RainfallServiceImpl;
import cn.edu.whu.forecast.service.impl.SectionServiceImpl;
import cn.edu.whu.forecast.service.impl.WarningRecordServiceImpl;
import cn.edu.whu.forecast.util.CSVFileUtil;
import cn.edu.whu.forecast.util.HttpClientUtil;
import cn.edu.whu.forecast.vo.request.AddWarningRecordVo;
import cn.edu.whu.forecast.vo.response.RainfallVo;
import cn.edu.whu.forecast.vo.response.RecordListVo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* 预报接口
* @author fullangleblank
* @since 2022/6/27
*/
@RestController
@Api(tags = "预报")
@RequestMapping("/forecast")
@CrossOrigin
public class ForecastController {
    @Resource
    private LogMessageServiceImpl logMessageService;
    @Resource
    private WarningRecordServiceImpl warningRecordService;
    @Resource
    private SectionServiceImpl sectionService;

    @Resource
    private RainfallServiceImpl rainfallService;
    @GetMapping("/getLogs")
    public PageBean<?> getLogs(
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam("startTime") LocalDateTime start,
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam("endTime") LocalDateTime end,
            @RequestParam("type") String type,
            int pageNum,
            int pageSize
    ){
        return logMessageService.GetLogs(start,end,type,pageNum,pageSize);
    }


    @GetMapping("/getWarningRecords")
    public PageBean<?> getWarningRecords(
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam("startTime") LocalDateTime start,
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam("endTime") LocalDateTime end,
            @Nullable @RequestParam("warning") Integer warning,
            int pageNum,
            int pageSize
    ){
        if (warning==null){
            return warningRecordService.getWarningRecord1(start,end,pageNum,pageSize);
        }
        else{
            return warningRecordService.getWarningRecord2(start,end,warning,pageNum,pageSize);
        }
    }

    @GetMapping("/getWarningRecordByTime")
    public ResultBean<?> getWarningRecordByTime(
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            @RequestParam("time") LocalDateTime time){
        return ResultBean.ok(warningRecordService.getWarningRecordByTime(time));
    }

    @GetMapping("/getWarningRecordsTimeList")
    public List<RecordListVo> getWarningRecordsTimeList(){
        return  warningRecordService.getWarningRecordTimeList();
    }

    @PostMapping("/addWarningRecord")
    public ResultBean<?> addWarningRecord(
            @RequestParam("criticalRainfall") BigDecimal criticalRainfall,
            @RequestParam("warning") Integer warning){
        AddWarningRecordVo addWarningRecordVo = new AddWarningRecordVo();
        addWarningRecordVo.setCriticalRainfall(criticalRainfall);
        addWarningRecordVo.setWarning(warning);
        warningRecordService.addWarningRecord(addWarningRecordVo);
        return ResultBean.ok();
    }

    @PostMapping("/deleteWarningRecord")
    public void deleteWarningRecord(
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            @RequestParam("time")
            LocalDateTime time){
        warningRecordService.deleteWarningRecord(time);
    }


    @GetMapping("/getWaterLevelAndFlowForecastByTimeAndDistrict")
    public ResultBean<?> getWaterLevelAndFlowForecastByTimeAndDistrict(
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            @RequestParam("time") LocalDateTime time,
            @RequestParam("sectionId") Integer sectionId
    ){
        time = time.minusMinutes(time.getMinute());
        time = time.minusSeconds(time.getSecond());
        return ResultBean.ok(sectionService.getWaterLevelAndFlowForecastByTimeAndDistrict(time, sectionId));
    }

    @GetMapping("/forecast")
    public ResultBean<?> forecast(
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            @RequestParam("time")  LocalDateTime time,
            @RequestParam("prd") Boolean prd
    ) throws IOException, ParseException {


        time = time.minusMinutes(time.getMinute());
        time = time.minusSeconds(time.getSecond());


        //testXlsx.xlsx

        //请求merge-single

        if(prd){
            HttpClientUtil.doGet("http://10.35.80.145:8082/merge");
        }else{
            String s1 = HttpClientUtil.doGet("http://10.35.80.145:8082/merge-single");
        }

        //请求radar

        String s2 = HttpClientUtil.doGet("http://10.35.80.145:8082/radar");

        //融合两个csv文件

        //写timepoint.csv文件

        List<List<Object>> heads = new ArrayList<>();
        List<Object> tmpHead = new ArrayList<>();
        tmpHead.add("point");
        tmpHead.add("time");
        heads.add(tmpHead);
        List<List<Object>> dataList=  new ArrayList<>();
        List<Object> data = new ArrayList<>();
        data.add("point");
        data.add("time");
        dataList.add(data);
        List<Object> data1 = new ArrayList<>();
        List<Object> data2 = new ArrayList<>();
        data1.add("pred_time");
        Date date= new Date();
        if(date.getMinutes()<15) date = new Date(date.getTime()-1000*60*60L);
        date.setMinutes(0);
        date.setSeconds(0);

        if(date.getMonth()<10){
            data1.add(new SimpleDateFormat("yyyy/M/dd HH:mm").format(date.getTime()));
            data2.add("pred_p_time");
            data2.add(new SimpleDateFormat("yyyy/M/dd HH:mm").format(date.getTime()+1000*60*60*24L));
        }else{
            data1.add(new SimpleDateFormat("yyyy/MM/dd HH:mm").format(date.getTime()));
            data2.add("pred_p_time");
            data2.add(new SimpleDateFormat("yyyy/MM/dd HH:mm").format(date.getTime()+1000*60*60*24L));
        }
        dataList.add(data1);
        dataList.add(data2);


        String fileName = "timepoint.csv";
        String filePath = "/home/shanhong/app/python/quanzhou/data/";

        CSVFileUtil.createCSV(heads,dataList,fileName,filePath,false);


        //调用xajPredict

        String s3 = HttpClientUtil.doGet("http://10.35.80.145:8082/xajPredict");

        String s4 = HttpClientUtil.doGet("http://10.35.80.145:8082/warningLevel");

        //处理返回结果

        JSONObject object = JSONObject.parseObject(s3);
        JSONObject warningLevel = JSONObject.parseObject(s4);
        String warningLevelString = warningLevel.getString("data");

        JSONArray data_flow = object.getJSONArray("dmFlowRate");
        JSONArray data_waterLevel = object.getJSONArray("dmWaterLevel");
        JSONArray date_criticalLevel = object.getJSONArray("criticalLevel");
        List<Integer> list = new ArrayList<>();
        list.add(2);
        list.add(12);
        list.add(13);
        list.add(55);
        list.add(58);
        list.add(69);
        list.add(91);
        list.add(92);
        list.add(119);

        for(int i=0; i<data_flow.size(); i++) {
            JSONArray data_flow_one = data_flow.getJSONArray(i);
            JSONArray data_waterLevel_one = data_waterLevel.getJSONArray(i);
            for(int j=0; j<data_flow_one.size()-1; j++){
                SectionFlowWaterLevel sectionFlowWaterLevel = new SectionFlowWaterLevel();
                sectionFlowWaterLevel.setSectionId(list.get(j));
                sectionFlowWaterLevel.setFlow(data_flow_one.getBigDecimal(j+1));
                sectionFlowWaterLevel.setWaterLevel(data_waterLevel_one.getBigDecimal(j+1));
                sectionFlowWaterLevel.setCreatTime(LocalDateTime.parse(data_flow_one.getString(0).replaceAll("T", " "), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

                sectionService.addFlowWaterLevel(sectionFlowWaterLevel);
            }
        }
        Integer has_merge = prd ? 1 : 0;
        switch (warningLevelString) {
            case "不预警":
                warningRecordService.addWarningRecord(new AddWarningRecordVo(date_criticalLevel.getBigDecimal(0), 0, has_merge));
                break;
            case "黄色预警":
                warningRecordService.addWarningRecord(new AddWarningRecordVo(date_criticalLevel.getBigDecimal(0), 1, has_merge));
                break;
            case "橙色预警":
                warningRecordService.addWarningRecord(new AddWarningRecordVo(date_criticalLevel.getBigDecimal(0), 2, has_merge));
                break;
            default:
                warningRecordService.addWarningRecord(new AddWarningRecordVo(date_criticalLevel.getBigDecimal(0), 3, has_merge));
                break;
        }

        //返回给前端
        return ResultBean.ok();
    }
}
